﻿#include "jlog.h"
#include "ui_jlog.h"
#include <QDebug>

JLog::JLog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::JLog)
{
    ui->setupUi(this);

    Init();
}

JLog::~JLog()
{
    delete LbLogo;
    delete LbServer;
    delete LbUser;
    delete LbPasswd;
    delete LbTipInfo;
    delete pBtnRefresh;
    delete LbVerCode;
    delete cBoxServer;
    delete cBoxUser;
    delete lEdtPasswd;
    delete pBtnLog;
    delete gLayInfo;
    delete Manage;
    for(int i = 0; i < AuthCodeList.size(); i++) {
        delete AuthCodeList.at(i).Label;
    }
    AuthCodeList.clear();
    delete ui;
}

void JLog::Init()
{
    // 初始化控件
    InitCtrls();
    // 初始化网络
    Manage = new QNetworkAccessManager(this);
    connect(Manage, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReceiveNetworkInfo(QNetworkReply*)));
    // 坐标
    Coords.clear();
    // 验证码
    QString url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand"; // 获取验证码
    Manage->get(QNetworkRequest(QUrl(url)));
}

void JLog::InitCtrls()
{
    LbLogo = new QLabel(QStringLiteral("Logo"));
    LbServer = new QLabel(QStringLiteral("服务器："));
    LbUser = new QLabel(QStringLiteral("用户名："));
    LbPasswd = new QLabel(QStringLiteral("密   码："));
    LbTipInfo = new QLabel(QStringLiteral("提示信息..."));
    LbVerCode = new QLabel(QStringLiteral("验证码"));
    cBoxServer = new QComboBox;
    cBoxUser = new QComboBox;
    lEdtPasswd = new QLineEdit;
    pBtnRefresh = new QPushButton(LbVerCode);
    pBtnLog = new QPushButton(QStringLiteral("登   录"));
    gLayInfo = new QGridLayout(this);
    gLayInfo->addWidget(LbLogo, 0, 1, 1, 2);
    gLayInfo->addWidget(LbServer, 1, 0);
    gLayInfo->addWidget(LbUser, 2, 0);
    gLayInfo->addWidget(LbPasswd, 3, 0);
    gLayInfo->addWidget(cBoxServer, 1, 1);
    gLayInfo->addWidget(cBoxUser, 2, 1);
    gLayInfo->addWidget(lEdtPasswd, 3, 1);
    gLayInfo->addWidget(pBtnLog, 4, 1);
    gLayInfo->addWidget(LbTipInfo, 5, 0, 1, 2);
    gLayInfo->addWidget(LbVerCode, 6, 0, 1, 2);
    // 设置边距，left, top, right, bottom
    gLayInfo->setContentsMargins(140, 0, 140, 0);
    // 设置行比例
    gLayInfo->setRowStretch(0, 3);
    gLayInfo->setRowStretch(1, 1);
    gLayInfo->setRowStretch(2, 1);
    gLayInfo->setRowStretch(3, 1);
    gLayInfo->setRowStretch(4, 1);
    gLayInfo->setRowStretch(5, 1);
    gLayInfo->setRowStretch(6, 5);
    // 登录按钮槽函数
    connect(pBtnLog, SIGNAL(clicked()), this, SLOT(OnpBtnLog()));
    // 设置水平间距(列间距)
    gLayInfo->setHorizontalSpacing(10);
    // 设置垂直间距(行间距)
    gLayInfo->setVerticalSpacing(10);
    // 设置Logo
    LbLogo->setAlignment(Qt::AlignCenter);
    // 设置验证码
    LbVerCode->setAlignment(Qt::AlignCenter);
    // 设置用户名下拉框可编辑
    cBoxUser->setEditable(true);
    // 设置服务器下拉框默认值
    cBoxServer->addItem(QStringLiteral("默认服务器"));
    // 设置验证码居中
    LbVerCode->setAlignment(Qt::AlignCenter);
    // 密码文本框显示
    lEdtPasswd->setEchoMode(QLineEdit::Password);
    // 默认值
    cBoxUser->addItem("13051034157");
    lEdtPasswd->setText("ll19931026");
    // 刷新按钮
    connect(pBtnRefresh, SIGNAL(clicked(bool)), this, SLOT(ObpBtnRefresh()));
    pBtnRefresh->setIcon(QIcon("Refresh.png"));
    pBtnRefresh->setStyleSheet("background: transparent;");
    pBtnRefresh->setGeometry(283, 0, 32, 32);
}

void JLog::OnpBtnLog()
{
    QNetworkRequest request;
    QUrl Url("https://kyfw.12306.cn/passport/captcha/captcha-check");
    QUrlQuery query;
    query.addQueryItem("login_site", "E");
    query.addQueryItem("rand", "sjrand");
    query.addQueryItem("answer", Coords); // "180,110,250,110"
    Url.setQuery(query);
    request.setUrl(Url);
    Manage->get(request);

    QString User = cBoxUser->currentText();
    QString Passwd = lEdtPasswd->text();
    Url = "https://kyfw.12306.cn/passport/web/login";
    query.addQueryItem("username", User);
    query.addQueryItem("password", Passwd);
    query.addQueryItem("appid", "otn");
    Url.setQuery(query);
    request.setUrl(Url);
    Manage->get(request);

    Coords.clear();
}

void JLog::ReceiveNetworkInfo(QNetworkReply *Info)
{
    QByteArray data = Info->readAll();
    QString str = data;
    qDebug() << str;
    if(!str.contains("result_code")) {
        QImage image;
        image.loadFromData(data, "jpg");
        LbVerCode->setPixmap(QPixmap::fromImage(image));
    }
    else {
        if(str.indexOf("4") != -1 && str.indexOf("uamtk") == -1) {
            LbTipInfo->setText(QStringLiteral("验证码校验成功"));
        }
        else if((str.indexOf("5") != -1 || str.indexOf("7") != -1 || str.indexOf("8") != -1) && str.indexOf("uamtk") == -1) {
            QString url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand"; // 获取验证码
            Manage->get(QNetworkRequest(QUrl(url)));
            Coords.clear();
        }
        else if(str.indexOf("0") != -1 && str.indexOf("uamtk") != -1) {
            LbTipInfo->setText(QStringLiteral("登录成功"));
            this->close();
        }
        else {
            qDebug() << "验证异常...";
        }
    }
}

void JLog::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::LeftButton) {
        if((e->pos().rx() >= LbVerCode->x()) && (e->pos().rx() <= LbVerCode->y() + LbVerCode->width()) &&
                (e->pos().ry() >= LbVerCode->y() + TITLEHIGH) && (e->pos().ry() <= LbVerCode->y() + LbVerCode->height())) {
            bool IsExist = false;
            for(int i = 0; i < AuthCodeList.size(); i++) {
                qDebug() << i << "; " << AuthCodeList.at(i).X - 15 << ", " << AuthCodeList.at(i).X + 15 << "; " <<
                            AuthCodeList.at(i).Y - 15 << ", " << AuthCodeList.at(i).Y + 15;
                if((e->pos().rx() >= AuthCodeList.at(i).X - 15) && (e->pos().rx() <= AuthCodeList.at(i).X + 15) &&
                        (e->pos().ry() >= AuthCodeList.at(i).Y - 15) && (e->pos().ry() <= AuthCodeList.at(i).Y + 15)) {
                    IsExist = true;
                    AuthCodeList.at(i).Label->hide();
                    delete AuthCodeList.at(i).Label;
                    AuthCodeList.remove(i);
                    break;
                }
            }
            if(!IsExist) {
                SelectPic Pic;
                QLabel *Label = new QLabel(this);
                QImage Img;
                Img.load("trainico.png");
                Label->setPixmap(QPixmap::fromImage(Img));
                Label->setGeometry(e->pos().rx() - 15, e->pos().ry() - 15, 30, 30);
                Label->show();
                Pic.Label = Label;
                Pic.X = e->pos().rx();
                Pic.Y = e->pos().ry();
                AuthCodeList.push_back(Pic);
                qDebug() << "Button click..";
            }
            if(Coords.isEmpty())
                Coords = QString("%1,%2").arg(e->pos().rx() - LbVerCode->x()).arg(e->pos().ry() - LbVerCode->y() - TITLEHIGH);
            else
                Coords.append(QString(",%1,%2").arg(e->pos().rx() - LbVerCode->x()).arg(e->pos().ry() - LbVerCode->y() - TITLEHIGH));
        }
    }
}

void JLog::ObpBtnRefresh()
{
    QString url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand"; // 获取验证码
    Manage->get(QNetworkRequest(QUrl(url)));
}
